package com.course.android.activity.ac;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Message;
import android.widget.TextView;
import android.location.LocationListener;
import android.location.LocationManager;
import android.util.Log;
import android.content.Context;
import android.os.Handler;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.course.android.R;
import com.course.android.activity.base.BaseActivity;

import java.text.SimpleDateFormat;

public class GpsActivity extends BaseActivity {

    private TextView textView = null;
    private Handler handler = null;

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void initView() {
        isPermission();
        checkGPSIsOpen(GpsActivity.this);
        //获取控件
        textView = findViewById(R.id.tv_gps_info);
        handler = new Handler(new Handler.Callback() {
            @SuppressLint("SetTextI18n")
            public boolean handleMessage(@NonNull Message message) {
                if (message.what == 123) {
                    Bundle bundle = (Bundle) message.obj;
                    //textView.setText("经度：" + bundle.getDouble("a1") + "纬度：" + bundle.getDouble("a2"));

                    textView.setText("经度："+bundle.getDouble("a1")+"\n纬度："+bundle.getDouble("a2")+
                            "\n海拔："+bundle.getDouble("a3")+"\n方向："+bundle.getFloat("a4")+"\nfrom： "+bundle.getString("a5")+
                            "\n"+bundle.getLong("a6")+"\n"+bundle.getString("a7"));
                    return true;
                }
                return false;
            }
        });
        beginLocation(GpsActivity.this);

    }

    @Override
    protected void initData() {

    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_gps;
    }

    @Override
    protected void onActivityResultCallBack(Integer reqCode, Intent data) {

    }

    @SuppressLint("NewApi")
    private void isPermission() {
        if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                || (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)){
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
        }
    }
    //获取定位功能状态
    public static boolean getGPSState(Context context){
        //获取定位管理器
        LocationManager locationManager= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    //确认定位功能是否开启，未开启则跳转至定位功能设置界面
    public static void checkGPSIsOpen(Context context){
        //未开启定位功能
        if(!getGPSState(context)){
            //跳转至定位功能设置界面
            Intent intent=new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            context.startActivity(intent);
        }
    }
    @SuppressLint("SetTextI18n")
    public void beginLocation(Context context) {
        //准备定位条件器
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);//高精度
        criteria.setPowerRequirement(Criteria.POWER_HIGH);
        criteria.setCostAllowed(true);
        criteria.setAltitudeRequired(true);//海拔
        criteria.setBearingRequired(true);//方向
        //获取定位管理器
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        //获取最佳定位提供者
        String provider = locationManager.getBestProvider(criteria, true);
//        LocationProvider provider = locationManager.getProvider(LocationManager.GPS_PROVIDER).get;
        if (provider != null) {
            //添加监听器
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            Log.d("OK","定位提供者为"+provider);
            //设置定位监听器；第一个参数为定位提供者，第二个参数为最小更新时间，第三个参数为最小更新距离，第四个参数为定位监听器
            locationManager.requestLocationUpdates(provider, 300, 0, new LocationListener() {
                Location oldLocation=null;
                //定位发生变化时触发
                public void onLocationChanged(@NonNull Location location) {
                    if (location != null) {
                        oldLocation=location;
                        Message message = new Message();
                        message.what = 123;
                        Bundle bundle = new Bundle();
                        bundle.putDouble("a1", location.getLongitude());
                        bundle.putDouble("a2", location.getLatitude());
                        bundle.putDouble("a3",location.getAltitude());
                        bundle.putFloat("a4",location.getBearing());
                        bundle.putString("a5",location.getProvider());
                        bundle.putLong("a6",location.getTime());
                        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String date=f.format(location.getTime());
                        bundle.putString("a7",date);
                        message.obj = bundle;
                        handler.sendMessage(message);
                    }
                }
                //定位提供者不可用时触发
                public void onProviderDisabled(@NonNull String provider) {
                    textView.setText("定位关停 - "+provider);
                }
                //定位提供者可用时触发
                @Override
                public void onProviderEnabled(@NonNull String provider) {
                    textView.setText("定位启动 - "+provider);
                    onLocationChanged(oldLocation);
                }
            });
            //获取最后结果
            Location location=locationManager.getLastKnownLocation(provider);
            if(location!=null){
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date=f.format(location.getTime());
                textView.setText("经度："+location.getLongitude()+"\n纬度："+location.getLatitude()+
                        "\n海拔："+location.getAltitude()+"\n方向："+location.getBearing()+"\nfrom： "+location.getProvider()+
                        "\n"+date);
            }
            else{
                textView.setText("无定位信息");
            }
        }
        else {
            textView.setText("定位功能未开启");
        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==1){
            for(int i=0;i<permissions.length;i++){
                if(grantResults[i]!=PackageManager.PERMISSION_GRANTED){
                    requestPermissions(new String[]{"android.permission.ACCESS_FINE_LOCATION"},1);
                    return;
                }
            }
            beginLocation(GpsActivity.this);
        }
    }

}